<template>
  <div class="loan-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="贷款编号" prop="loanNo">
          <el-input
            v-model="searchForm.loanNo"
            placeholder="请输入贷款编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="贷款类型" prop="loanType">
          <el-select
            v-model="searchForm.loanType"
            placeholder="请选择贷款类型"
            clearable
            style="width: 120px"
          >
            <el-option label="个人消费贷" value="personal" />
            <el-option label="住房贷款" value="house" />
            <el-option label="车辆贷款" value="car" />
            <el-option label="经营贷款" value="business" />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待审核" value="pending" />
            <el-option label="审核通过" value="approved" />
            <el-option label="已放款" value="disbursed" />
            <el-option label="已结清" value="closed" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已逾期" value="overdue" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增贷款</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 贷款列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="loanNo" label="贷款编号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="loanType" label="贷款类型" width="120">
          <template #default="scope">
            {{ getLoanTypeText(scope.row.loanType) }}
          </template>
        </el-table-column>
        <el-table-column prop="loanAmount" label="贷款金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="loanTerm" label="贷款期限" width="120">
          <template #default="scope">
            {{ scope.row.loanTerm }}个月
          </template>
        </el-table-column>
        <el-table-column prop="interestRate" label="年利率" width="100">
          <template #default="scope">
            {{ scope.row.interestRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="monthlyPayment" label="月供" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.monthlyPayment) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getLoanStatusType(scope.row.status)">
              {{ getLoanStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 贷款详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      title="贷款详情" 
      width="60%"
      :before-close="handleDetailClose"
    >
      <loan-detail v-if="detailVisible" :loan-id="currentLoanId" />
    </el-dialog>
    
    <!-- 贷款审批历史对话框 -->
    <el-dialog 
      v-model="historyVisible" 
      title="审批历史" 
      width="60%"
      :before-close="handleHistoryClose"
    >
      <approval-history v-if="historyVisible" :loan-id="currentLoanId" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { loanApplyApi } from '@/api/loan'
import LoanDetail from './components/LoanDetail.vue'
import ApprovalHistory from './components/ApprovalHistory.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const detailVisible = ref(false)
const historyVisible = ref(false)
const currentLoanId = ref('')
const dateRange = ref([])

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  loanType: '',
  status: '',
})

// 格式化钱数
const formatMoney = (amount) => {
  return amount ? '¥' + amount.toLocaleString() : '¥0'
}

// 获取贷款类型文本
const getLoanTypeText = (type) => {
  const map = {
    personal: '个人消费贷',
    house: '住房贷款',
    car: '车辆贷款',
    business: '经营贷款'
  }
  return map[type] || type
}

// 获取贷款状态文本
const getLoanStatusText = (status) => {
  const map = {
    pending: '待审核',
    approved: '审核通过',
    disbursed: '已放款',
    closed: '已结清',
    rejected: '已拒绝',
    overdue: '已逾期'
  }
  return map[status] || status
}

// 获取状态标签类型
const getLoanStatusType = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    disbursed: 'success',
    closed: 'info',
    rejected: 'danger',
    overdue: 'danger'
  }
  return map[status] || ''
}

// 获取贷款列表
const getList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    console.log('调用接口参数:', params)
    
    try {
      const res = await loanApplyApi.getList(params)
      console.log('接口返回数据:', res)
      
      if (res.code === 200 || res.code === '200') {
        // 处理不同的数据结构
        let listData = []
        let totalCount = 0
        
        // 检查返回数据结构
        if (res.data && res.data.list) {
          // 新的数据结构: {code:"200", msg:"操作成功", data:{total:6, pageSize:10, list:[...], pageNum:1}}
          listData = res.data.list
          totalCount = res.data.total
        } else if (res.data && res.data.data && res.data.data.list) {
          // 嵌套结构: {code:200, msg:"", data:{code:200, msg:"", data:{list:[], total:0}}}
          listData = res.data.data.list
          totalCount = res.data.data.total
        } else if (res.data && Array.isArray(res.data)) {
          // 直接返回数组: {code:200, data:[...]}
          listData = res.data
          totalCount = res.data.length
        } else {
          console.warn('未识别的返回数据结构:', res)
          listData = []
          totalCount = 0
        }
        
        tableData.value = listData
        total.value = totalCount
        
        if (!listData || listData.length === 0) {
          ElMessage.warning('未查询到贷款数据')
        }
      } else {
        ElMessage.error(res.msg || res.message || '获取贷款列表失败')
      }
    } catch (error) {
      console.error('接口调用失败，使用本地数据:', error)
    }
  } catch (error) {
    console.error('获取贷款列表出错:', error)
    ElMessage.error(`获取贷款列表失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []
  currentPage.value = 1
  getList()
}

// 新增贷款
const handleAdd = () => {
  router.push('/loan/apply')
}

// 编辑贷款
const handleEdit = (row) => {
  router.push(`/loan/apply?id=${row.id}`)
}

// 查看贷款详情
const handleView = (row) => {
  currentLoanId.value = row.id
  detailVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentLoanId.value = ''
}

// 查看审批历史
const handleViewHistory = (row) => {
  currentLoanId.value = row.id
  historyVisible.value = true
}

// 关闭历史对话框
const handleHistoryClose = () => {
  historyVisible.value = false
  currentLoanId.value = ''
}

// 审批贷款
const handleApproval = (row) => {
  router.push(`/loan/approval?id=${row.id}`)
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.loan-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 